'use strict';

/* Controllers */
app.controller('SigninCtrl', ['$scope', '$window', '$rootScope', '$state', 'userService', function ($scope, $window, $rootScope, $state, userService) {
    $scope.user = {};
    $scope.authError = null;
    $scope.showE = false;
    $window.sessionStorage.clear();
    $rootScope.loginUser = null;
    $scope.isCaptchaChecked = true;

    function getCaptcha() {
        $("#captchaImg").attr("src", "captcha/get?t=" + Math.random());
    };
    getCaptcha();

    $scope.validateCaptcha = function () {
        if ($scope.validateCode) {
            $.ajax({
                url: "captcha/validate",
                type: "post",
                contentType: "application/json;charset='UTF-8'",
                data: JSON.stringify({
                    pm1: $scope.validateCode
                }),
                dataType: 'json',
                success: function (response) {
                    $scope.isCaptchaChecked = response['success'];
                },
                error: function (error) {
                    alert(error);
                }
            });
        }
    };

    $scope.changeCaptcha = function () {
        getCaptcha();
    };

    $scope.login = function () {
        $scope.authError = null;
        $scope.showE = false;

        var salt = "1a2b3c4d5e6f7g8h9j0k";
        var mPass = hex_md5(salt.charAt(0) + salt.charAt(2) + $scope.user.password + salt.charAt(5) + salt.charAt(9));

        $.ajax({
            url: "sysuser/login",
            type: "post",
            contentType: "application/json;charset='UTF-8'",
            data: JSON.stringify({
                account: $scope.user.username,
                password: mPass,
                code: $scope.validateCode
            }),
            dataType: 'json',
            success: function (response) {
                // $state.go('app.main');

                if (response && response['code'] == 0) {
                    userService.setData(response.data);
                    $state.go('app.main');
                } else {
                    $scope.authError = response['message'];
                    $scope.showE = true;
                    $scope.$apply();
                }
            },
            error: function (error) {
                $scope.authError = '服务器异常，请稍后在试！';
            }
        });
    };

}])
;